<template>
  <div class="product-container">
    <el-card class="box-card">
      <!-- 搜索区域 -->
      <el-form :inline="true" :model="searchForm">
        <el-form-item label="商品名称">
          <el-input v-model="searchForm.name" placeholder="请输入商品名称"/>
        </el-form-item>
        <el-form-item label="商品分类">
          <el-select v-model="searchForm.categoryId" placeholder="请选择分类" style="width: 180px">
            <el-option
                v-for="item in categoryList"
                :key="item.id"
                :label="item.categoryName"
                :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">查询</el-button>
          <el-button @click="resetSearch">重置</el-button>
        </el-form-item>
      </el-form>

      <!-- 操作按钮 -->
      <div class="operation-area">
        <el-button type="primary" @click="handleAdd">新增商品</el-button>
      </div>

      <!-- 表格 -->
      <el-table :data="productList" border style="width: 100%">
        <el-table-column type="index" label="序号" width="60"/>
        <el-table-column prop="productName" label="商品名称"/>
        <el-table-column prop="price" label="价格" width="100"/>
        <el-table-column prop="stock" label="库存" width="100"/>
        <el-table-column prop="categoryName" label="分类" width="100"/>
        <el-table-column prop="description" show-overflow-tooltip label="描述" width="180"/>
        <el-table-column prop="createTime" label="创建时间" width="180"/>
        <el-table-column label="操作" width="180" fixed="right">
          <template #default="{ row }">
            <el-button type="primary" link @click="handleEdit(row)">编辑</el-button>
            <el-button type="danger" link @click="handleDelete(row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination">
        <el-pagination
            v-model:current-page="page"
            v-model:page-size="pageSize"
            :page-sizes="[10, 20, 30, 50]"
            :total="total"
            layout="total, sizes, prev, pager, next, jumper"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <el-dialog :title="productForm.categoryId ? '修改商品' : '新增商品'" v-model="dialogVisible">
      <el-form label-width="auto" :model="productForm">
        <el-form-item label="商品名称" prop="name">
          <el-input v-model="productForm.productName" placeholder="请输入商品名称"/>
        </el-form-item>
        <el-form-item label="价格" prop="price">
          <el-input v-model="productForm.price" placeholder="请输入价格"/>
        </el-form-item>
        <el-form-item label="库存" prop="stock">
          <el-input v-model="productForm.stock" placeholder="请输入库存"/>
        </el-form-item>
        <el-form-item label="描述" prop="description">
          <el-input type="textarea" v-model="productForm.description" placeholder="请输入描述"/>
        </el-form-item>
        <el-form-item label="分类" prop="categoryId">
          <el-select v-model="productForm.categoryId" placeholder="请选择分类" style="width: 180px">
            <el-option
                v-for="item in categoryList"
                :key="item.id"
                :label="item.categoryName"
                :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="productFormSubmit">保存</el-button>
          <el-button @click="dialogVisible = false">取消</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import {onMounted, reactive, ref} from 'vue'
import {reqAddProduct, reqDeleteProduct, reqProductList} from "@/apis/product";
import {ProductData} from "@/apis/product/type.ts";
import {CategoryData} from "@/apis/category/type.ts";
import {reqCategoryList} from "@/apis/category";
import {ElMessage, ElMessageBox} from "element-plus";

const searchForm = ref({
  name: '',
  categoryId: ''
})

const page = ref(1)
const pageSize = ref(10)
const total = ref(0)
let categoryList = ref<CategoryData[]>([])
let productList = ref<ProductData[]>([])

// 新增商品表单
const dialogVisible = ref(false)
const productForm:any = reactive({
  productName: '',
  price: '',
  stock: '',
  description: '',
  categoryId: ''
})


// 获取分类列表
const getCategoryList = async () => {
  const result = await reqCategoryList({})
  if (result.code === 200) {
    categoryList.value = result.data.records
  }
}

// 获取商品列表
const getProductList = async (pager = 1, name = '') => {
  page.value = pager
  const result = await reqProductList({
    name: name.valueOf(),
    page: page.value,
    size: pageSize.value,
    categoryId: searchForm.value.categoryId
  })
  if (result.code === 200) {
    productList.value = result.data.records
    total.value = result.data.total
    await getCategoryList()
  }
}


// 搜索
const handleSearch = () => {
  getProductList(1, searchForm.value.name)
}

// 重置搜索
const resetSearch = () => {
  searchForm.value = {
    name: '',
    categoryId: ''
  }
  getProductList()
}

// 新增商品
const handleAdd = () => {
  dialogVisible.value = true
  Object.assign(productForm, {
    productName: '',
    price: '',
    stock: '',
    description: '',
    categoryId: ''
  })
}

// 保存商品
const productFormSubmit = async () => {
  const result = await reqAddProduct(productForm)
  if(result.code === 200){
    dialogVisible.value = false
    await getProductList()
    ElMessage.success('新增商品成功')
  }
}

// 编辑商品
const handleEdit = (row: any) => {
  Object.assign(productForm, row);
  productForm.categoryId = row.categoryName
  dialogVisible.value = true;
}

// 删除商品
const handleDelete = async (row: any) => {
  try {
    await ElMessageBox.confirm('确定要删除该商品吗？', '提示', {
      type: 'warning'
    })
    await reqDeleteProduct(row.id)
    ElMessage.success('删除成功')
    await getProductList(productList.value.length === 1 ? page.value - 1 : page.value)
  } catch (error: any) {
    if (error !== 'cancel') {
      ElMessage.error(error.message || '删除失败')
    }
  }
}

// 分页相关
const handleSizeChange = () => {
  getProductList()
}

const handleCurrentChange = () => {
  getProductList()
}

onMounted(() => {
  getProductList()
})
</script>

<style scoped lang="scss">
.product-container {
  .operation-area {
    margin: 15px 0;
  }

  .pagination {
    margin-top: 20px;
    display: flex;
    justify-content: flex-end;
  }
}
</style> 